package spring_cloud.demo.game_hystrix;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class GameService {

	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	RestTemplate restTemplate;
	
	@HystrixCommand(fallbackMethod="connectToServerFallBack") String conectToServer(String userName, String password) {
		Map<String, Object> uriVariables = new HashMap<>();
		uriVariables.put("name", userName);
		uriVariables.put("password", password);
		return restTemplate.getForEntity("http://SSO-SERVICE/login?userName={name}&password={password}", String.class,uriVariables).getBody();
	}
	
	public String connectToServerFallBack(String userName, String password) {
		return "Failed to connect to game server.";
	}
	
	
	@HystrixCommand(fallbackMethod="connectToServerFallBack") String conectToUnstableServer(String userName, String password) {
		long start =  System.currentTimeMillis();
		try {
			int time = new Random().nextInt(2_000);
			Thread.sleep(time);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		String result = conectToServer(userName,password);
		long end =  System.currentTimeMillis();
		logger.info("take time: "+(end-start)/1000.0+" s");
		return result;
	}
	
	
}
